package com.youdoneed.base.common;

import org.springframework.data.redis.connection.RedisConnectionFactory;

/**
 * Redis存储对象操作类，支持复杂对象。
 *
 * @author Ewing
 */
public class RedisForObject {

    private RedisConnectionFactory connectionFactory;

    public RedisForObject(RedisConnectionFactory connectionFactory) {
        this.connectionFactory = connectionFactory;
    }

    private byte[] getNumberBytes(Number key) {
        long temp = key.longValue();
        byte[] bytes = new byte[8];
        for (int i = 0; i < bytes.length; i++) {
            bytes[i] = (byte) (temp & 0xff);
            temp = temp >> 8; // 向右移8位
        }
        return bytes;
    }

    public void putObject(String key, Object object) {
        byte[] values = ProtostuffSerializer.serialize(object);
        connectionFactory.getConnection().set(key.getBytes(), values);
    }

    public void putObject(String key, Object object, long seconds) {
        byte[] values = ProtostuffSerializer.serialize(object);
        connectionFactory.getConnection().setEx(key.getBytes(), seconds, values);
    }

    public <T> T getObject(String key) {
        byte[] values = connectionFactory.getConnection().get(key.getBytes());
        return ProtostuffSerializer.deserialize(values);
    }

    public void putObject(Number key, Object object) {
        byte[] bytes = getNumberBytes(key);
        byte[] values = ProtostuffSerializer.serialize(object);
        connectionFactory.getConnection().set(bytes, values);
    }

    public void putObject(Number key, Object object, long seconds) {
        byte[] bytes = getNumberBytes(key);
        byte[] values = ProtostuffSerializer.serialize(object);
        connectionFactory.getConnection().setEx(bytes, seconds, values);
    }

    public <T> T getObject(Number key) {
        byte[] bytes = getNumberBytes(key);
        byte[] values = connectionFactory.getConnection().get(bytes);
        return ProtostuffSerializer.deserialize(values);
    }

    public void putObject(Object key, Object object) {
        byte[] keys = ProtostuffSerializer.serialize(key);
        byte[] values = ProtostuffSerializer.serialize(object);
        connectionFactory.getConnection().set(keys, values);
    }

    public void putObject(Object key, Object object, long seconds) {
        byte[] keys = ProtostuffSerializer.serialize(key);
        byte[] values = ProtostuffSerializer.serialize(object);
        connectionFactory.getConnection().setEx(keys, seconds, values);
    }

    public <T> T getObject(Object key) {
        byte[] keys = ProtostuffSerializer.serialize(key);
        byte[] values = connectionFactory.getConnection().get(keys);
        return ProtostuffSerializer.deserialize(values);
    }

}
